import request, { extend } from 'umi-request';
import { message } from 'antd';
import { UserForm } from './data';

const errorHandler = function(error:any) {
  if (error.response) {
    if(error.response.status>=400){
      message.error(error.data.message ? error.data.message : error.data);
    }
  } else {
    message.error("网络故障");
  }
  //throw error; // If throw. The error will continue to be thrown.
};

const extendRequest = extend({ errorHandler });

export const getRemoteList = async () => {
    return extendRequest('/api/users', {
        method: 'get',
      }).then(function(response) {
          return response;
      })
      .catch(function(error) {
          return false;
      });
};

export const editUser = async({id,values}:{id:number,values:UserForm})=>{
  return extendRequest(`/api/users/${id}`,{
    method:'put',
    data:values,
  }).then(function(response){
    return true;
  }).catch(function(error){
    return false;
  });
};

export const addUser = async({values}:{values:UserForm})=>{
  return extendRequest(`/api/users`,{
    method:'post',
    data:values,
  }).then(function(response){
    return true;
  }).catch(function(error){
    return false;
  });
};

export const delUser = async({id}:{id:number}) =>{
  return extendRequest(`/api/users/${id}`,{
    method:'delete'
  }).then(function(response){
    return true;
  }).catch(function(error){
    return false;
  });
};